//
//  BDRedWhiteViewController.m
//  BadBoy
//
//  Created by wen on 2017/3/23.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDRedWhiteViewController.h"
#import "BDRedEnvelopeModel.h"
#import "BDUserModel.h"
#import "BDMoneyRedEnvelopeTableViewCell.h"
#import "BDPostRedEnvelopeTableViewCell.h"

@interface BDRedWhiteViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;


@property (nonatomic, strong) UIButton *seletedButton;
@property (nonatomic, strong) NSString *type;
@end

@implementation BDRedWhiteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    if (self.chooseFinishedBlock == nil) {
        [self layoutSubviews];
        [self requestDatasource];
    }else{
        self.title = ASLocalizedString(@"选择红包");
        [self.tableView reloadData];
    }

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)layoutSubviews{
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 44)];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 2)];
    lineView.backgroundColor =KBDColorBlue;
    [titleView addSubview:lineView];
    
    CGFloat allWidth = 0;
    NSArray *titleArray = @[ASLocalizedString(@"优惠红包"), ASLocalizedString(@"主题红包")];
    for (int i = 0; i < titleArray.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:titleArray[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithHexString:@"#767676"] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithHexString:@"#ffffff"] forState:UIControlStateSelected];
        button.titleLabel.font = [UIFont systemFontOfSize:17];
        button.size = CGSizeMake([titleArray[0] widthWithFont:button.titleLabel.font] + 20, 44);
        button.left = allWidth;
        [titleView addSubview:button];
        allWidth = button.right;
        if (i == 0) {
            button.selected = YES;
            lineView.width = button.width;
            lineView.left = button.left;
            lineView.bottom = titleView.height;
            self.seletedButton = button;
            self.type = @"2";
        }
        [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (button.selected == YES) {
                return;
            }
            [UIView animateWithDuration:0.3 animations:^{
                lineView.left = button.left;
            } completion:^(BOOL finished) {
                self.seletedButton.selected = NO;
                button.selected = YES;
                self.seletedButton = button;
                if (i == 0) {
                    self.type = @"2";
                }else{
                    self.type = @"1";
                }
                [self.datasource removeAllObjects];
                [self requestDatasource];
            }];
        }];
    }
    titleView.width = allWidth;
    self.navigationItem.titleView = titleView;
}

- (void)requestDatasource{
    [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
    NSString *url = [NSString stringWithFormat:@"%@hongBaos?page=1&size=50&type=%@&status=1", KBDBaseURL, self.type];
    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *redEnvelopeSignal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [redEnvelopeSignal subscribeNext:^(id  _Nullable x) {
        [MBManager hideAlert];
        [self.datasource addObjectsFromArray:[BDRedEnvelopeModel mj_objectArrayWithKeyValuesArray:x[@"list"]]];
        for (BDRedEnvelopeModel *redEnvelope in self.datasource) {
            redEnvelope.isEffective = YES;
        }
        [self.tableView reloadData];
        self.isEnd = YES;
        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
    }];
    [redEnvelopeSignal subscribeError:^(NSError * _Nullable error) {
        [MBManager hideAlert];
        [self showErrorViewWithTapBlock:^{
            [self requestDatasource];
        }];
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 146;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDRedEnvelopeModel *model = self.datasource[indexPath.section];
    BDBaseTableViewCell *cell = nil;
    if (model.type == BdRedEnvelopeTypeMoney) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"moneyCell" forIndexPath:indexPath];
    }else if (model.type == BdRedEnvelopeTypePost) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"postCell" forIndexPath:indexPath];
    }
    [cell configeWithModel:self.datasource[indexPath.section]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BDRedEnvelopeModel *model = self.datasource[indexPath.section];
    if (model.type == BdRedEnvelopeTypePost) {
        if (self.chooseFinishedBlock) {
            self.chooseFinishedBlock(self.datasource[indexPath.section]);
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else if (model.type == BdRedEnvelopeTypeMoney && model.isEffective == YES) {
        if (self.chooseFinishedBlock) {
            self.chooseFinishedBlock(self.datasource[indexPath.section]);
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStyleGrouped];
        _tableView.sectionFooterHeight = 0;
        _tableView.sectionHeaderHeight = 0;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[BDMoneyRedEnvelopeTableViewCell class] forCellReuseIdentifier:@"moneyCell"];
        [_tableView registerClass:[BDPostRedEnvelopeTableViewCell class] forCellReuseIdentifier:@"postCell"];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray array];
    }
    return _datasource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
